#!flask/bin/python
import io
import os
from threading import Lock

from flask import Flask, render_template, render_template_string, request, send_file
from celery import Celery

REDIS_IP = "106.52.222.179"
REDIS_PORT = 26379
REDIS_PWD = "redis20201124"

# 初始化 Celery
app = Flask(__name__)
celery = Celery(app.name, broker=f'redis://:{REDIS_PWD}@{REDIS_IP}:{REDIS_PORT}/0')
celery.conf.update(app.config)

port = 5002

@app.route("/")
def index():
    return render_template(
        "index_gauss.html"
    )

lock = Lock()

def is_chinese_char(char):
    """判断单个字符是否为中文字符"""
    return '\u4e00' <= char <= '\u9fa5'

def is_all_chinese(text):
    """判断字符串是否全部由中文字符组成"""
    return all(is_chinese_char(c) for c in text)

def contains_chinese(text):
    """判断字符串中是否包含中文字符"""
    return any(is_chinese_char(c) for c in text)

# 全局变量用于存储 TTS 模型
tts = None

@celery.task
def generate_tts(text, style_wav):
    global tts
    if tts is None:
        from TTS.api import TTS
        tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=False)
    if contains_chinese(text):
        wavs = tts.tts(text=text,
                       speaker_wav=style_wav,
                       language="zh-cn")
    else:
        wavs = tts.tts(text=text,
                       speaker_wav=style_wav,
                       language="en")
    out = io.BytesIO()
    tts.synthesizer.save_wav(wavs, out)
    out.seek(0)
    return out

import time
@app.route("/api/tts", methods=["GET", "POST"])
def api_tts():
    start_time = time.time()  # 总耗时起点
    # 1. 参数解析阶段
    parse_start = time.time()
    with lock:
        text = request.headers.get("text") or request.values.get("text", "")
        style_wav = request.headers.get("style-wav") or request.values.get("style_wav", "")
        style_wav = f"speaker/{style_wav}-sample.wav"
        parse_time = time.time() - parse_start
        print(f" > Model input: {text}")
        # 异步调用 Celery 任务
        task = generate_tts.delay(text, style_wav)
    # 计算总耗时
    total_time = time.time() - start_time
    # 记录详细耗时日志（可替换为日志系统）
    print(f"[TTS API] 总耗时: {total_time:.3f}s | 参数解析: {parse_time:.3f}s")
    # 可选：在响应头中返回耗时信息和任务 ID
    # 返回任务 ID 给客户端
    return {
        'message': 'TTS 任务已启动',
        'task_id': str(task.id),
        'process_time': f"{total_time:.3f}s"
    }, 202

    response = send_file(task.get(), mimetype="audio/wav")
    response.headers['X-Process-Time'] = f"{total_time:.3f}s"
    response.headers['X-Task-ID'] = str(task.id)
    return response


def main():
    app.run(debug=False, host="0.0.0.0", port=port)


if __name__ == "__main__":
    main()